package ide.ccf.ccproject.wizards.pages;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.sql.Timestamp;

import ide.ccf.ccproject.ProjectPlugin;
import ide.ccf.ccproject.common.Utils;
import ide.ccf.ccproject.data.FileInfo;
import ide.ccf.ccproject.preferences.PreferenceConstants;
import ide.ccf.ccproject.translate.Message;
import ide.ccf.ccproject.wizards.ExportCpkWizard;

import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.PreferencesUtil;

public class ExportSelectFolderWizardPage extends WizardPage implements SelectionListener {
		Composite p;
		public static Text sfoldername;
		public static Text foldername;
		public static Text ccffoldername;
		public static Text sName_1, sName_2, sName_3;
		public static String wholeName;
		public static String sfoldernamePath_cache, spath, exportPath, sharePath, filesPath, ccfAppPath;
		private static final String tooltip =
				Message.ExportCpkWizard_5 +
				Message.ExportCpkWizard_6 +
				Message.ExportCpkWizard_7; 
	public ExportSelectFolderWizardPage(String pageName) {
		super(pageName);
		p = null;
		setTitle(pageName);
		setDescription(Message.ExportCpkWizard_2);
		setPageComplete(false);
		sfoldernamePath_cache  = null;
		spath = null;
		exportPath = null;
		sharePath = null;
		filesPath = null;
		ccfAppPath = null;
	}


	public void createControl(Composite parent) {
		Composite control = new Composite(parent, SWT.CLOSE);
		GridLayout lay = new GridLayout();
		lay.verticalSpacing = 1;
		control.setLayout(lay);
		control.setLayoutData(new GridData(GridData.FILL_BOTH));
		control.setSize(control.computeSize(500, 300));
		setControl(control);
		p = parent;
		
		Composite workArea = new Composite(control, SWT.CLOSE);
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		layout.verticalSpacing = 1;
		workArea.setLayout(layout);
		workArea.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
		workArea.setSize(workArea.computeSize(500, 300));
		
		final Group g1 = new Group(workArea,SWT.NONE);
		g1.setText(Message.ExportCpkWizard_3);
		GridData gd1 = new GridData(GridData.FILL_BOTH);
		g1.setLayoutData(gd1);
		GridLayout _layout = new GridLayout(2,false);
		g1.setLayout(_layout);
		sfoldername = new Text(g1, SWT.BORDER);
		sfoldername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		Button browse = new Button(g1, SWT.NONE);
		browse.setText(Message.UiFileWizardPage_11);
		browse.addSelectionListener(this);
		g1.setToolTipText(tooltip);
		
		final Group g2 = new Group(workArea,SWT.NONE);
		g2.setText(Message.ExportCpkWizard_4);
		GridData gd2 = new GridData(GridData.FILL_BOTH);
		g2.setLayoutData(gd2);
		GridLayout _layout2 = new GridLayout(2,false);
		g2.setLayout(_layout2);
		foldername = new Text(g2, SWT.BORDER);
		foldername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		g2.setToolTipText(Message.ExportCpkWizard_8);
		Button browse2 = new Button(g2, SWT.NONE);
		browse2.setText(Message.UiFileWizardPage_11);
		browse2.addMouseListener( new MouseListener(){
			public void mouseDoubleClick(MouseEvent e) {
			}
			public void mouseDown(MouseEvent e) {
				Shell shell = p.getShell();
				DirectoryDialog dlg = new DirectoryDialog(shell);
		        dlg.setFilterPath("cccc");
		        dlg.setText(Message.ExportCpkWizard_4);
		        dlg.setMessage(Message.ExportCpkWizard_10);
		        String dir = dlg.open();
		        if (dir != null) 
		        {
		        	foldername.setText(dir);
		        }
			}
			public void mouseUp(MouseEvent e) {
			}
		});
		
		String ccfpath = getCCFPath();
		final Group g3 = new Group(workArea,SWT.NONE);
		g3.setText(Message.ExportCpkWizard_15);
		GridData gd3 = new GridData(GridData.FILL_BOTH);
		g3.setLayoutData(gd3);
		GridLayout _layout3 = new GridLayout(2,false);
		g3.setLayout(_layout3);
		ccffoldername = new Text(g3, SWT.BORDER);
		ccffoldername.setText(ccfpath==null ? "" : ccfpath);
		ccffoldername.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		Button browse3 = new Button(g3, SWT.NONE);
		browse3.setText(Message.UiFileWizardPage_11);
		browse3.addMouseListener( new MouseListener(){
			public void mouseDoubleClick(MouseEvent e) {
			}
			public void mouseDown(MouseEvent e) {
				Shell shell = p.getShell();
				DirectoryDialog dlg = new DirectoryDialog(shell);
		        dlg.setFilterPath("cccc");
		        dlg.setText(Message.ExportCpkWizard_15);
		        dlg.setMessage(Message.ExportCpkWizard_15);
		        String dir = dlg.open();
		        if (dir != null) 
		        {
		        	ccffoldername.setText(dir);
		        	IPreferenceStore store = ProjectPlugin.getDefault().getPreferenceStore();
					store.setValue(PreferenceConstants.CCF_PATH, dir);
		        }   	
			}
			public void mouseUp(MouseEvent e) {
			}
		});
		g3.setToolTipText(Message.ExportCpkWizard_14);
			
		final Group g4 = new Group(workArea,SWT.NONE);
		g4.setText(Message.ExportCpkWizard_16);
		GridData gd4 = new GridData(GridData.FILL_BOTH);
		g4.setLayoutData(gd4);
		GridLayout _layout4 = new GridLayout(5,false);
		g4.setLayout(_layout4);
		g4.setToolTipText(Message.ExportCpkWizard_17);
		sName_1 = new Text(g4, SWT.BORDER);
		GridData _gd = new GridData(GridData.FILL_HORIZONTAL);
        _gd.widthHint = 30;
        sName_1.setLayoutData(_gd);
		Label occupy_1 = new Label(g4, SWT.NULL);
		occupy_1.setText(".");
		sName_2 = new Text(g4, SWT.BORDER);
		GridData _gd3 = new GridData(GridData.FILL_HORIZONTAL);
		_gd3.widthHint = 30;
        sName_2.setLayoutData(_gd3);
		Label occupy_2 = new Label(g4, SWT.NULL);
		occupy_2.setText(".");
		sName_3 = new Text(g4, SWT.BORDER);
		GridData _gd5 = new GridData(GridData.FILL_HORIZONTAL);
		_gd5.widthHint = 30;
        sName_3.setLayoutData(_gd5);
	
		Label occupy = new Label(workArea, SWT.NONE);
		Label occupy1 = new Label(workArea, SWT.NONE);
		Button bGenerate = new Button(workArea, SWT.RIGHT_TO_LEFT);
		bGenerate.setText(Message.ExportCpkWizard_18);
		
		
		Group gr = new Group(control, SWT.NONE);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		gd.horizontalSpan = 2;
		gr.setLayoutData(gd);
		gr.setLayout(new FillLayout());
		Label lb = new Label(gr, SWT.NONE);
		lb.setText(Message.ExportCpkWizard_22);
	
		bGenerate.addMouseListener(new MouseListener(){
			public void mouseDoubleClick(MouseEvent e) {
				// TODO 自动生成的方法存根
			}

			public void mouseDown(MouseEvent e) {
				// TODO 自动生成的方法存根
				if(!sfoldername.getText().trim().isEmpty()
						&& !foldername.getText().trim().isEmpty()
						&& !ccffoldername.getText().trim().isEmpty()
						&& !sName_1.getText().trim().isEmpty()
						&& !sName_2.getText().trim().isEmpty()
						&& !sName_3.getText().trim().isEmpty()
						&& new File(sfoldername.getText().trim()).isDirectory()
						&& new File(ccffoldername.getText().trim()).isDirectory()
						&& new File(foldername.getText().trim()).isDirectory())
				{
					wholeName = sName_1.getText().trim() + "." + sName_2.getText().trim() + "." + sName_3.getText().trim();
					//先获取处理器类型　例如i386
					if(Utils.runCommand("ccf --default-arch", 1).equals("1"))
					{
						setDescription(Message.ExportCpkWizard_23);
						ccfAppPath = ccffoldername.getText().trim() + "/app";
						//执行拷贝动作前先删除/app文件目录下原有的文件
						String oldpath = sfoldernamePath_cache  + ccfAppPath;
						deleteOldFiles(oldpath);
						String arch = Utils.runCommand("ccf --default-arch", 0);
						spath = sfoldernamePath_cache  + ccfAppPath + "/" + wholeName + "/" + arch.trim() + "/";//TODO 处理器类型需要读取本地处理器类型
						String[] p  = spath.split("/");
						String path = "";
						for(int i = 0; i < p.length; i++)
						{
							path +=  p[i] +"/";
						    File file = new File(path);
						    //判断文件夹是否存在,如果不存在则创建文件夹
						    if (!file.exists()) 
							    file.mkdir();
						}
						
						exportPath = spath + "/" +"export";
						sharePath =  spath + "/" +"export" + "/" + "share";
						filesPath = spath +"/" + "files";
						String[] newPath =  new String[]{exportPath, sharePath, filesPath};
						for(int j = 0; j < newPath.length; j++)
						{
								File file = new File(newPath[j]);
								if(!file.exists())
									file.mkdir();
						}
						//拷贝文件到files里面
						copyGenerateFile(sfoldername.getText().trim(), filesPath);
						//在files目录下生成.ref隐藏文件(暂时这么处理)
						generateRefFile(filesPath);
						//在源文件夹外层目录寻找metadata文件拷贝至生成文件目录中
						String s = sfoldername.getText().trim();
						copyMetadataFile(sfoldername.getText().trim(), filesPath);
						setPageComplete(true);	
						setDescription(Message.ExportCpkWizard_19);
					}
					else
					{
						setPageComplete(false);	
						setDescription(Message.ExportCpkWizard_20);
					}
				}
				else
				{
					setPageComplete(false);	
					setDescription(Message.ExportCpkWizard_21);
				}	
			}
			
			public void mouseUp(MouseEvent e) {
				// TODO 自动生成的方法存根
				
			}
		});
	}
	
	
	//删除指定文件夹下所有文件
	//param path 文件夹完整绝对路径
	   private boolean deleteOldFiles(String path) 
	   {
	       boolean flag = false;
	       File file = new File(path);
	       if (!file.exists()) {
	         return flag;
	       }
	       if (!file.isDirectory()) {
	         return flag;
	       }
	       String[] tempList = file.list();
	       File temp = null;
	       for (int i = 0; i < tempList.length; i++) {
	          if (path.endsWith(File.separator)) {
	             temp = new File(path + tempList[i]);
	          } else {
	              temp = new File(path + File.separator + tempList[i]);
	          }
	          if (temp.isFile()) {
	             temp.delete();
	          }
	          if (temp.isDirectory()) {
	        	  deleteOldFiles(path + "/" + tempList[i]);//先删除文件夹里面的文件
	             delFolder(path + "/" + tempList[i]);//再删除空文件夹
	             flag = true;
	          }
	       }
	       return flag;
	    }


 private void delFolder(String folderPath)
 {
     try {
    	 deleteOldFiles(folderPath); //删除完里面所有内容
        String filePath = folderPath;
        filePath = filePath.toString();
        java.io.File myFilePath = new java.io.File(filePath);
        myFilePath.delete(); //删除空文件夹
     } catch (Exception e) {
       e.printStackTrace(); 
     }
}
 
 private String  getFileList(String strPath) {
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
		for (int i = 0; i < files.length; i++) 
		{
		String fileName = files[i].getName();
		if (files[i].isDirectory()) 
		{ // 判断是文件还是文件夹
			getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
		} 
		else if (fileName.equals("metadata")) 
		{ // 判断文件名是否是metadata
			String strFileName = files[i].getAbsolutePath();
			return strFileName;
			
		} else {
				continue;
			}
		}
		}
		return null;
	}
 
 private boolean copyMetadataFile(String first, String last)
 {
	 File f = new File(last);
	 f = f.getParentFile();
	 last = f.getAbsolutePath() + "/metadata";
	 //(最多往上层目录递归查找两层)寻找metadate文件，直接拷贝至目标文件相关位置
	 f = new File(first);
	 if(!f.getParentFile().isDirectory())
	   return false;
	 f = f.getParentFile();
	 String metapath = getFileList(f.getAbsolutePath());
	 if(metapath != null)
		 Utils.copyFile(metapath, last);
	 else
	 {
		 if(!f.getParentFile().isDirectory())
			   return false;
		 f = f.getParentFile();
		 metapath = getFileList(f.getAbsolutePath());
		 if(metapath != null)
			 Utils.copyFile(metapath, last);
	 }
	 return true;
 }
 
 private void generateRefFile(String filesPath)
 {
     File file = new File(filesPath + "/.ref");
     if(!file.getParentFile().exists())
     {
    	 file.getParentFile().mkdirs();
     }
     try {
		file.createNewFile();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
 }

	private boolean copyGenerateFile(String srcPath, String destPath) {
		boolean flag = false;
		// TODO 自动生成的方法存根
		File file = new File(srcPath);
		if(!file.exists()) // 源文件或源文件夹不存在
			return false;
		if(file.isFile()) //文件复制
			flag = Utils.copyFile(srcPath, destPath, true);
		else if(file.isDirectory())//文件夹复制
		{
			File srcFile = new File(srcPath);
			File[] fileList = srcFile.listFiles();    //获取源文件夹下的子文件和子文件夹
			   if(fileList.length==0) {    // 如果源文件夹为空目录则直接设置flag为true，这一步非常隐蔽，debug了很久
		            flag = true;
		        }
		        else {
		            for(File temp: fileList) {
		                if(temp.isFile()) {    // 文件
		                    flag = Utils.copyFile(temp.getAbsolutePath(), destPath, true);     // 递归复制时也继承覆盖属性
		                }
		                else if(temp.isDirectory()) {    // 文件夹
		                    flag = Utils.copyDirectory(temp.getAbsolutePath(), destPath, true);   // 递归复制时也继承覆盖属性
		                }

		                if(!flag) {
		                    break;
		                }
		            }
		        }
		}
		return flag;
	}

	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO 自动生成的方法存根
		
	}
	
	public void widgetSelected(SelectionEvent e) {
		Shell shell = p.getShell();
		DirectoryDialog dlg = new DirectoryDialog(shell);
        dlg.setFilterPath("cccc");
        dlg.setText(Message.ExportCpkWizard_3);
        dlg.setMessage(Message.ExportCpkWizard_9);
        String dir = dlg.open();   
        if (dir != null) 
        {
        	sfoldername.setText(dir);
        	sfoldernamePath_cache  = dir + "_cahce";
        	//System.out.println("设置路径成功"+ dir);
        	 String pathCPK  = sfoldernamePath_cache  +"/CPK/";
        	File file = new File(pathCPK);
        	if(file.isDirectory() && file.exists())
        	{
        	    //如果CPK文件夹包含相关文件，直接展现在界面上。
     			setXml(pathCPK);
     			setInstall(pathCPK);
     			setDesktop(pathCPK);
     			setFilelist(pathCPK);
     		
    			ExportSetInfoWizardPage t = ExportCpkWizard.setInfoPage;
    			t.setPageComplete(ExportSetInfoWizardPage.bXml && ExportSetInfoWizardPage.bInstall && ExportSetInfoWizardPage.bFilelist);
    			}	
        	else
        	{
        		file.mkdirs();
        		/*ExportSetInfoWizardPage.table.clearAll();
        		ExportSetInfoWizardPage.table.setItemCount(0);
                ExportSetInfoWizardPage.table.setSize(535, 275);
                for (int i = 0; i < 4 ; i++) {
                    new TableItem(ExportSetInfoWizardPage.table, SWT.NONE).setText("");
                }*/	
        	}
        	}
        }

	private void setFilelist(String pathCPK)
	{
		String filePath = pathCPK+ "filelist";
		if(Utils.isExistFile(filePath) )
		{
			File fs = new File(filePath);
			long	modify = fs.lastModified();
			FileInfo	f = new FileInfo("filelist", pathCPK, new  Timestamp(modify).toString());
				//ExportSetInfoWizardPage.list.add(f);
				 //设置表格数据  
				int	n = ExportSetInfoWizardPage.table4.getItemCount();
				for(int i = 0; i < n; ++i)
				{
					 TableItem item =ExportSetInfoWizardPage. table4.getItem(i);
					 if(item.getText().trim().equals("filelist") ||item.getText().trim().isEmpty())
					 {
						 item.setText(f.toArray()); 
			             break;
					 }
				}  
				ExportSetInfoWizardPage.bFilelist = true;
				ExportSetInfoWizardPage.tips4.setVisible(true);
		}
	}
	
	private void setXml(String pathCPK)
	{
		String xml = pathCPK + "control.xml";
		if(Utils.isExistFile(xml) )
		{
			//获取文件创建的时间
			File fs  =  new File(xml); 
			long modify = fs.lastModified();
			FileInfo f = new FileInfo("control.xml", pathCPK, new  Timestamp(modify).toString());
			//ExportSetInfoWizardPage.list.add(f);
			 //设置表格数据  
			int n = ExportSetInfoWizardPage.table.getItemCount();
			for(int i = 0; i < n; ++i)
			{
				 TableItem item = ExportSetInfoWizardPage.table.getItem(i);
				 if(item.getText().trim().equals("control.xml") || item.getText().trim().isEmpty())
				 {
					 item.setText(f.toArray()); 
		             break;
				 }
			} 
			ExportSetInfoWizardPage.bXml = true;
			ExportSetInfoWizardPage.tips.setVisible(true);
		}
	}
	
	private  void setDesktop(String cpkPath)
	  {
	    File f = new File(cpkPath);
	     if (f.exists() && f.isDirectory())
	     {
	       if (f.listFiles().length > 0)
	       {
	         String[] file1 = f.list(new FilenameFilter(){//使用匿名内部类重写accept方法
	            public boolean accept(File dir, String name){
	                if(new File(dir,name).isDirectory()){
	                    return true;
	                }
	                return name.indexOf(".desktop")!=-1;//筛选出.desktop文件
	            }
	        }
	);
	         if(file1.length > 1)
	         {
	        	 for(int j = 0; j < file1.length -1; j++)
	        		 new TableItem(ExportSetInfoWizardPage.table3, SWT.NONE).setText("");
	         }

             for (int j = 0; j < file1.length; j++)
	         {
            	 File afile = new File(cpkPath+"/"+file1[j]);
            	  if(afile.isFile())
            	  {
            			long modify = afile.lastModified();
    					FileInfo fs = new FileInfo(afile.getName(), cpkPath, new  Timestamp(modify).toString());
    					//ExportSetInfoWizardPage.list.add(fs);
    					 //设置表格数据  
    					int n =ExportSetInfoWizardPage.table3.getItemCount();
    					for(int i = 0; i < n; ++i)
    					{
    						 TableItem item =ExportSetInfoWizardPage. table3.getItem(i);
    						 if(item.getText().trim().equals(afile.getName()) || item.getText().trim().isEmpty())
    						 {
    							 item.setText(fs.toArray()); 
    				             break;
    						 }
    					}   
            	  }
	         }
             if(file1.length > 0)
            	 ExportSetInfoWizardPage.tips3.setVisible(true);
	       }
	     }
	  } 
	
	private  void setInstall(String cpkPath)
	  {
	    File f = new File(cpkPath);
	     if (f.exists() && f.isDirectory())
	     {
	       if (f.listFiles().length > 0)
	       {
	         String[] file1 = f.list(new FilenameFilter(){//使用匿名内部类重写accept方法
	            public boolean accept(File dir, String name){
	                if(new File(dir,name).isDirectory()){
	                    return true;
	                }
	                return name.indexOf(".install")!=-1;//筛选出.install文件
	            }
	        }
	);

           for (int j = 0; j < file1.length; j++)
	       {
          	 File afile = new File(cpkPath+"/"+file1[j]);
          	  if(afile.isFile())
          	  {
          			long modify = afile.lastModified();
  					FileInfo fs = new FileInfo(afile.getName(), cpkPath, new  Timestamp(modify).toString());
  					//ExportSetInfoWizardPage.list.add(fs);
  					 //设置表格数据  
  					int n =ExportSetInfoWizardPage. table2.getItemCount();
  					for(int i = 0; i < n; ++i)
  					{
  						 TableItem item =ExportSetInfoWizardPage. table2.getItem(i);
  						 if(item.getText().trim().equals(afile.getName()) || item.getText().trim().isEmpty())
  						 {
  							 item.setText(fs.toArray()); 
  				             break;
  						 }
  					}   
  					ExportSetInfoWizardPage.bInstall = true;
  					ExportSetInfoWizardPage.tips2.setVisible(true);
          	  }
	      }
	   }
	  }
  } 
	
	public static String  getCCFPath() {
		if(ProjectPlugin.getDefault() != null)
		{
			IPreferenceStore store = ProjectPlugin.getDefault().getPreferenceStore();
			
			if (!store.contains(PreferenceConstants.CCF_PATH))
				return null;
			
			String defaultpath = store.getString(PreferenceConstants.CCF_PATH);
			return defaultpath;
	
		}
		return null;
	}
}
